/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package manager.auxiliares;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author diego1
 */
public class FixedLengthDocument extends PlainDocument {

    private int iMaxLength;

    public FixedLengthDocument(int maxlen) {
        super();
        iMaxLength = maxlen;
    }

    @Override
    public void insertString(int offset, String str, AttributeSet a)
            throws BadLocationException {
        if (str == null) {
            return;
        }
        if (iMaxLength <= 0) // aceitara qualquer no. de caracteres
        {
            super.insertString(offset, str, a);
            return;
        }
        char[] upper = str.toCharArray();
        for (int i = 0; i < upper.length; i++) {
            upper[i] = Character.toUpperCase(upper[i]);
        }
        str = new String(upper);
        int ilen = (getLength() + str.length());
        if (ilen <= iMaxLength) // se o comprimento final for menor...
        {

            super.insertString(offset, str, a);   // ...aceita str
            } else {
            if (getLength() == iMaxLength) {
                return; // nada a fazer
                }
            String newStr = str.substring(0, (iMaxLength - getLength()));

            super.insertString(offset, newStr, a);
        }
    }
}
   
